package com.wzdigit.wms.raw.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * 请求方法拦截日志
 *
 * @author hsiang
 * @date 2018年11月23日 下午1:11:18
 * @version 0.1.0
 * @copyright Wzdigit Information Technology (Huizhou) Co.,Ltd.
 */
public class LogHandlerInterceptor implements HandlerInterceptor {

	private static final Logger LOGGER = LoggerFactory.getLogger(LogHandlerInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		if (handler instanceof HandlerMethod) {
			StringBuilder sbf = new StringBuilder();
			sbf.append(">>>>>>>>>>")
			  .append(SimpleDateFormat.getDateTimeInstance().format(new Date()))
			  .append(">>>>>>>>>");
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			sbf.append("Controller:").append(handlerMethod.getBean().getClass().getName()).append(",");
			sbf.append("Method:").append(handlerMethod.getMethod().getName()).append(",");
			sbf.append("Params:").append(getParamString(request.getParameterMap())).append(",");
			//判断注解获取
			Method method = handlerMethod.getMethod();
			method.getTypeParameters();
			sbf.append("URL:").append(request.getRequestURL()).append("");
			LOGGER.info(sbf.toString());
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	private String getParamString(Map<String, String[]> map) {
        StringBuilder sbf = new StringBuilder();
        for(Entry<String,String[]> e:map.entrySet()){
            sbf.append(e.getKey()).append("=");
            String[] value = e.getValue();
            if(value != null && value.length == 1){
                sbf.append(value[0]).append("\t");
            }else{
                sbf.append(Arrays.toString(value)).append("\t");
            }
        }
        return sbf.toString();
    }

}
